from django.shortcuts import render
from django.views import View
from .models import Area
from django.http import JsonResponse
from django.core.cache import cache
# Create your views here.
class ProvinceAreasView(View):
    def get(self,request):
        province_list = cache.get('province_list')
        if not province_list:
            province_list = []
            provinces = Area.objects.filter(parent=None)
            for province in provinces:
                province_list.append({'id':province.id,'name':province.name})
            cache.set('province_list',province_list,3600)

        return JsonResponse({'code':0,'errmsg':'OK','province_list':province_list})

class SubAreasView(View):
    def get(self,request,pk):
        province = Area.objects.get(id=pk)
        sub_list = cache.get('sub_list')
        if not sub_list:
            sub_list = []
            subs = Area.objects.filter(parent = province.id)
            for sub in subs:
                print(province.id, province.name)
                sub_list.append({'id': sub.id, 'name': sub.name})
            cache.set('sub_list',sub_list,3600)
        sub_data = {
            'id':province.id,
            'name':province.name,
            'subs':sub_list
        }
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'sub_data': sub_data})

